import { BASE_URL } from './config'

// 防止多次触发401处理
let handling401Error = false;

const request = (url, options = {}) => {
  return new Promise((resolve, reject) => {
    // 从本地存储获取token
    const token = wx.getStorageSync('token') || {}
    // 默认请求头
    const header = {
      'Content-Type': 'application/json'
    }

    // 如果有token，添加到请求头
    if (token) {
      header['Authorization'] = `Bearer ${token}`
    }

    wx.request({
      url: `${BASE_URL}${url}`,
      ...options,
      header,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else if (res.statusCode === 401) {
          // 防止多次同时触发401处理
          if (handling401Error) {
            console.log('request: 已有401处理正在进行，忽略此次请求');
            reject(res);
            return;
          }

          handling401Error = true;
          console.log('request: 收到401错误', url);

          // 处理未授权情况
          wx.showToast({
            title: '登录信息已过期，请重新登录',
            icon: 'none',
            duration: 2000
          });

          // 延迟调用登录弹窗，确保Toast已显示
          setTimeout(() => {
            console.log('request: 准备调用认证管理器');
            try {
              const app = getApp();
              if (app && app.globalData && app.globalData.authManager) {
                console.log('request: 通过全局authManager显示登录弹窗');
                app.globalData.authManager.showLoginPopup();
              } else if (app && app.showLoginPopup) {
                console.log('request: 通过app.showLoginPopup显示登录弹窗');
                app.showLoginPopup();
              } else {
                console.error('request: 无法获取认证管理器');
                // 直接尝试跳转到首页
                wx.switchTab({
                  url: '/pages/index/index'
                });
              }
            } catch (err) {
              console.error('request: 调用登录弹窗出错', err);
            } finally {
              // 延迟重置处理状态
              setTimeout(() => {
                handling401Error = false;
              }, 2000);
            }
          }, 300);

          reject(res)
        } else {
          reject(res)
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

const showError = (error) => {
  wx.showToast({
    title: error.errMsg || '请求失败',
    icon: 'none',
    duration: 2000
  })
}

// GET请求
const get = (url, data = {}) => {
  return request(url, {
    method: 'GET',
    data
  })
}

// POST请求
const post = (url, data = {}) => {
  return request(url, {
    method: 'POST',
    data
  })
}

// PUT请求
const put = (url, data = {}) => {
  return request(url, {
    method: 'PUT',
    data
  })
}

// DELETE请求
const del = (url, data = {}) => {
  return request(url, {
    method: 'DELETE',
    data
  })
}

// 请求拦截器
const requestInterceptor = () => {
  const token = wx.getStorageSync('token')
  if (token) {
    return {
      header: {
        'Authorization': `Bearer ${token}`
      }
    }
  }
  return {}
}

export {
  get,
  post,
  put,
  del,
  requestInterceptor
}